package com.lagou.edu.authority.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.lagou.edu.authority.contant.MenuContants;
import com.lagou.edu.authority.dto.AllocateRoleMenuDTO;
import com.lagou.edu.authority.dto.MenuNodeDTO;
import com.lagou.edu.authority.entity.Menu;
import com.lagou.edu.authority.entity.RoleMenu;
import com.lagou.edu.authority.mapper.MenuMapper;
import com.lagou.edu.authority.service.IMenuService;
import com.lagou.edu.authority.service.IRoleMenuService;
import com.lagou.edu.common.util.ConvertUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * TODO
 *
 * @author lm
 * @since 2021/11/4 15:49
 */
@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements IMenuService {
    @Autowired
    MenuMapper menuMapper;

    @Autowired
    IRoleMenuService roleMenuService;

    @Override
    public List<MenuNodeDTO> getMenuNodeList() {
        List<Menu> topLevelMenuList = lambdaQuery()
                .eq(Menu::getLevel, MenuContants.MENU_TOP_LEVEL)
                .list();
        if (CollectionUtils.isEmpty(topLevelMenuList)) {
            return Lists.newArrayList();
        }
        List<MenuNodeDTO> menuNodeList = topLevelMenuList.stream().map(menu -> fillMenuNode(menu)).collect(Collectors.toList());
        Collections.sort(menuNodeList);
        return menuNodeList;
    }

    /**
     * 查询子菜单
     *
     * @param menu
     */
    public MenuNodeDTO fillMenuNode(Menu menu) {
        List<Menu> subMenuList = lambdaQuery()
                .eq(Menu::getParentId, menu.getId())
                .list();
        MenuNodeDTO menuNodeDTO = ConvertUtils.convert(menu, MenuNodeDTO.class);
        if (CollectionUtils.isEmpty(subMenuList)) {
            return menuNodeDTO;
        }
        List<MenuNodeDTO> subMenuNodeDTOList = subMenuList.stream().map(subMenu -> fillMenuNode(subMenu)).collect(Collectors.toList());
        Collections.sort(subMenuNodeDTOList);
        menuNodeDTO.setSubMenuList(subMenuNodeDTOList);
        return menuNodeDTO;
    }

    @Override
    public List<Menu> getMenuByRoleId(Set<Integer> roleIds) {
        if (CollectionUtils.isEmpty(roleIds)) {
            return Lists.newArrayList();
        }
        return menuMapper.queryByRoleIds(roleIds);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean allocateRoleMenus(AllocateRoleMenuDTO allocateRoleMenuDTO) {
        if (CollectionUtils.isEmpty(allocateRoleMenuDTO.getMenuIdList())) {
            // 表示删除所有角色菜单
            allocateRoleMenuDTO.setMenuIdList(Lists.newArrayList());
        }
        // 角色已拥有的菜单
        Set<Integer> roleMenuIds = roleMenuService.getMenuIdListByRoleIds(Sets.newHashSet(allocateRoleMenuDTO.getRoleId()));
        // 准备分配给角色的菜单，排除掉 -1(-1是不存在的id，是顶级菜单的父ID)
        Set<Integer> allocateRoleMenuIds = allocateRoleMenuDTO.getMenuIdList().stream()
                .filter(menuId -> !Objects.equals(menuId, MenuContants.MENU_TOP_LEVEL_PARENT_ID)).collect(Collectors.toSet());

        // 找出本次删除的
        Set<Integer> needToDelMenus = roleMenuIds.stream().filter(id -> !allocateRoleMenuIds.contains(id)).collect(Collectors.toSet());
        // 找出本次新增的
        Set<Integer> needToInsertMenus = allocateRoleMenuIds.stream().filter(id -> !roleMenuIds.contains(id)).collect(Collectors.toSet());

        if (!CollectionUtils.isEmpty(needToDelMenus)) {
            // 删除角色关联的菜单
            roleMenuService.removeRoleMenuIdList(allocateRoleMenuDTO.getRoleId(), needToDelMenus);
        }

        if (!CollectionUtils.isEmpty(needToInsertMenus)) {
            List<RoleMenu> roleMenus = needToInsertMenus.stream().map(menuId -> {
                RoleMenu roleMenu = new RoleMenu();
                roleMenu.setRoleId(allocateRoleMenuDTO.getRoleId());
                roleMenu.setMenuId(menuId);
                roleMenu.setCreatedBy(allocateRoleMenuDTO.getCreatedBy());
                roleMenu.setUpdatedBy(allocateRoleMenuDTO.getUpdatedBy());
                roleMenu.setCreatedTime(new Date());
                roleMenu.setUpdatedTime(new Date());
                return roleMenu;
            }).collect(Collectors.toList());
            return roleMenuService.saveBatch(roleMenus);
        }
        return Boolean.TRUE;
    }
}
